﻿using CMS.Business;
using CMS.Business.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CMS.Web.Helpers
{
    public static class MenuHelpers
    {
        public static string MenuPage(this HtmlHelper helper, int languageId)
        {
            string menu = string.Empty;
            
            try
            {
                menu = "<div><ul class='sf-menu'>";
                IPageBussiness PageBussiness = Provider.Resolve<IPageBussiness>();
                List<PageViewModel> listPageViewModel = PageBussiness.GetAllPagesByLanguageId(languageId);
                List<PageSubPageViewModel> listSubPageViewModel = PageBussiness.GetAllPageSubPage();
                foreach (PageViewModel pageViewModel in listPageViewModel.Where(o => o.PageId == o.PageFamilyId).ToList())
                {
                    string menuTemp = CreateMenu(pageViewModel, listPageViewModel, listSubPageViewModel);
                    menu += menuTemp;
                }
                menu += "</ul></div>";
            }
            catch
            {
            }

            return menu;
        }

        private static string CreateSubMenu(string action, string controller, string pageName)
        {
            string menu = string.Empty;
            menu = "<li><a href='#'>" + pageName + "</a></li>";

            return menu;
        }

        private static string CreateMenu(PageViewModel pageViewModel, List<PageViewModel> listPageViewModel, List<PageSubPageViewModel> listPageSubPageViewModel)
        {
            string menuString = string.Empty;
            menuString += "<li>{0}";
            var mn = from xdata in listPageSubPageViewModel
                     where xdata.PageId == pageViewModel.PageId
                     select xdata;
            mn = mn.Where(o => !(listPageViewModel.Where(i => i.PageId == o.SubPageId).FirstOrDefault() == null));            

            if (mn != null && mn.ToList().Count > 0)
            {
                menuString = string.Format(menuString, "<a>" + pageViewModel.PageName + "</a>");
                menuString += "<ul>";
                foreach (PageSubPageViewModel pageSubModel in mn.ToList())
                {
                    
                    PageViewModel p = new PageViewModel();
                    p = listPageViewModel.Where(o => o.PageId == pageSubModel.SubPageId).FirstOrDefault();
                    menuString += CreateMenu(p, listPageViewModel, listPageSubPageViewModel);
                }
                menuString += "</ul>";
            }
            else
            {
                menuString = string.Format(menuString, "<a>" + pageViewModel.PageName + "</a>");
            }

            menuString += "</li>";

            return menuString;
        }
    }
}